package com.moon.ws;

/**
 * @author Chenzy
 * @create 2023-03-30 19:00
 */
import com.github.pagehelper.PageInfo;
import com.moon.entity.TAuctionItem;
import com.moon.service.TAuctionItemService;
import com.moon.utils.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.CrossOrigin;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint("/webSocket/{auctionId}")
@Component
@CrossOrigin("*")
public class WebSocket {

    private static Map<String, List<WebSocket>> clients = new ConcurrentHashMap();
    private Session session;

    @Autowired
    private TAuctionItemService tAuctionItemService;


    @OnOpen
    public void onOpen(@PathParam("auctionId") String auctionId, Session session) {

        try{
            this.session = session;
            if (!clients.containsKey(auctionId)){
                clients.put(auctionId,new ArrayList<>());
            }
            clients.get(auctionId).add(this);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @OnClose
    public void onClose(@PathParam("auctionId") String auctionId) {
        clients.get(auctionId).remove(this);
    }


    //接受前端send的消息
    @OnMessage
    public void onMessage(String message) {
        System.out.println(message);
//        PageInfo<TAuctionItem> pageInfo = tAuctionItemService.getItemByAuctionId(Long.parseLong(message), 1, 3);

        String auctionId = this.session.getPathParameters().get("auctionId");

        //然后发送List<AuctionItemVo>给该竞拍室id的所有session
        sendMessage("changed",auctionId);


    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        System.out.println("error:" + throwable.getMessage());
    }


    //向前端onmessage发送String消息
    public static void sendMessage(String message , String auctionId) {
        // 向所有连接websocket的客户端发送消息
        // 可以修改为对某个客户端发消息
        for (WebSocket item : clients.get(auctionId)) {
            item.session.getAsyncRemote().sendText(message);
        }
    }


}